﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using DropBoxTool.Model;
using Microsoft.Phone.Controls;
using NetworkDetection;
using ResumeMusicPlayTest;

namespace DropBoxTool
{
    public partial class MusicPlayer : ViewModelPageClassWithQuery
    {
        public MusicPlayer()
        {
            InitializeComponent();
            if (IsInDesignMode)
            {
                File = new NavigatableDropBoxFolderItem
                {
                    FullPath = "testing\testing file.jpg",
                    IsDirectory = false
                };
            }
            Unloaded += new RoutedEventHandler(MusicPlayer_Unloaded);
            mediaElement.CurrentStateChanged += new RoutedEventHandler(mediaElement_CurrentStateChanged);
            mediaElement.MediaOpened += new RoutedEventHandler(mediaElement_MediaOpened);
            mediaElement.MediaEnded += new RoutedEventHandler(mediaElement_MediaEnded);
            mediaElement.MediaFailed += new EventHandler<ExceptionRoutedEventArgs>(mediaElement_MediaFailed);
            //mediaElement.
        }

        protected void DisplayDebugMessage(string message)
        {
#if DEBUG
            DebugMessage.Text = message;
            DevMessagePopup.Visibility = System.Windows.Visibility.Visible;
#endif
        }

        private void DevPopupOk_Click(object sender, RoutedEventArgs e)
        {
            DevMessagePopup.Visibility = System.Windows.Visibility.Collapsed;
        }

        void mediaElement_MediaFailed(object sender, ExceptionRoutedEventArgs e)
        {
            DisplayDebugMessage(e.ErrorException.ToString());
            playing = false;
        }

        void mediaElement_MediaEnded(object sender, RoutedEventArgs e)
        {
            playing = false;
            NextButton_Click(this, null);
        }

        void mediaElement_MediaOpened(object sender, RoutedEventArgs e)
        {
            playing = true;
            mediaElement.Play();
        }

        void mediaElement_CurrentStateChanged(object sender, RoutedEventArgs e)
        {
            var x = 1;
        }

        void MusicPlayer_Unloaded(object sender, RoutedEventArgs e)
        {
            mediaElement.Stop();
            XnaMusicUtil.RestoreCurrentMediaState();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            XnaMusicUtil.SaveCurrentMediaState();
            base.OnNavigatedTo(e);
            if (!IsInDesignMode)
            {
                // TODO: load Image
                var fullPath = QueryString["file"] ?? "";
                LoadMusic(fullPath);
            }
        }

        bool playing = false;

        private void LoadMusic(string fullPath)
        {
            var net = NetworkDetector.Instance.GetCurrentNetworkType();
            var zune = NetworkDetector.Instance.GetZuneStatus();
            var x = NetworkDetector.Instance.GetRequestStatus();
            Message = "";
            if (!String.IsNullOrEmpty(fullPath))
            {
                progressIndicator.Visibility = Visibility.Visible;
                DropBoxController.Inst.Api.GetFile(fullPath, (isoPath, ex) =>
                {
                    Dispatcher.BeginInvoke(() =>
                    {
                        if (ex == null)
                        {
                            var lastResult = DropBoxController.Inst.Api.GetLastListingResults(fullPath);
                            file = NavigatableDropBoxFolderItem.FromBaseType(lastResult);

                            using (var isoFS = IsolatedStorageFile.GetUserStoreForApplication())
                            {
                                if (isoFS.FileExists(isoPath))
                                {
                                    using (var fs = IsolatedStorageFile.GetUserStoreForApplication().OpenFile(isoPath, FileMode.Open))
                                    {
                                        mediaElement.Stop();
                                        mediaElement.AutoPlay = false;
                                        mediaElement.SetSource(fs);
                                        mediaElement.Position = System.TimeSpan.FromSeconds(0);
                                        mediaElement.Volume = 1;
                                        playing = false;
                                    }
                                }
                                else
                                {
                                    // TODO: notify user no file
                                    Message = "FYI: File not downloaded yet (Network may be down)";
                                }
                            }
                            if (FolderInfo == null)
                                FolderInfo = NavigatableDropBoxFolderItem.FromBaseType(DropBoxController.Inst.Api.GetLastListingResults(file.FilePath));
                        }
                        else
                        {
                            // TODO: notify the user of an error
                            Message = "FYI: An error occurred while trying to get this file (Network might have just gone down)";
                        }

                        progressIndicator.Visibility = Visibility.Collapsed;
                    });
                });
            }
        }

        private NavigatableDropBoxFolderItem folderInfo = null;

        public NavigatableDropBoxFolderItem FolderInfo
        {
            get
            {
                return folderInfo;
            }
            set
            {
                folderInfo = value;
                RaisePropertyChanged("FolderInfo");
            }
        }

        protected string message = "";

        public string Message
        {
            get { return message; }
            set
            {
                message = value;
                RaisePropertyChanged("Message");
            }
        }

        protected NavigatableDropBoxFolderItem file = null;

        public NavigatableDropBoxFolderItem File
        {
            get { return file; }
            set
            {
                file = value;
                RaisePropertyChanged("File");
            }
        }

        private void PrevButton_Click(object sender, RoutedEventArgs e)
        {
            var q = (from fileItem in folderInfo.Contents
                     where Array.IndexOf(NavigatableDropBoxFolderItem.musicTypes, System.IO.Path.GetExtension(fileItem.FullPath).ToUpper()) != -1 &&
                     fileItem.Name.CompareTo(file.Name) < 0
                     orderby fileItem.Name descending
                     select fileItem).FirstOrDefault();
            if (q == null)
            {
                q = (from fileItem in folderInfo.Contents
                     where Array.IndexOf(NavigatableDropBoxFolderItem.musicTypes, System.IO.Path.GetExtension(fileItem.FullPath).ToUpper()) != -1
                     orderby fileItem.Name
                     select fileItem).LastOrDefault();
            }

            if (q != null)
            {
                LoadMusic(q.FullPath);
            }
        }

        private void NextButton_Click(object sender, RoutedEventArgs e)
        {
            var q = (from fileItem in folderInfo.Contents
                     where Array.IndexOf(NavigatableDropBoxFolderItem.musicTypes, System.IO.Path.GetExtension(fileItem.FullPath).ToUpper()) != -1 &&
                     fileItem.Name.CompareTo(file.Name) > 0
                     orderby fileItem.Name
                     select fileItem).FirstOrDefault();
            if (q == null)
            {
                q = (from fileItem in folderInfo.Contents
                     where Array.IndexOf(NavigatableDropBoxFolderItem.musicTypes, System.IO.Path.GetExtension(fileItem.FullPath).ToUpper()) != -1
                     orderby fileItem.Name
                     select fileItem).FirstOrDefault();
            }

            if (q != null)
            {
                LoadMusic(q.FullPath);
            }
        }
    }
}